package com.wowangz.cms.systemmanage.currency.api;

import java.util.Date;
import java.util.HashMap;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.wowangz.cms.common.pojo.AjaxDataEntity;
import com.wowangz.cms.common.utils.SysConstant;
import com.wowangz.cms.component.datagrid.pojo.DataGrid;
import com.wowangz.cms.component.datagrid.pojo.DataResult;
import com.wowangz.cms.component.datagrid.pojo.DataStyle;
import com.wowangz.cms.component.datagrid.pojo.PangingParam;
import com.wowangz.cms.component.datagrid.utils.DataTypeConstant;
import com.wowangz.cms.component.datagrid.utils.PangingTools;
import com.wowangz.cms.syscore.IssTransactionContainer;
import com.wowangz.cms.syscore.api.BaseController;
import com.wowangz.cms.syscore.api.JSONFactory;
import com.wowangz.cms.syscore.exception.ServiceException;
import com.wowangz.cms.syscore.utils.MessageResourcesUtils;
import com.wowangz.cms.syscore.utils.ServletUtils;
import com.wowangz.cms.systemmanage.currency.pojo.Currency;
import com.wowangz.cms.systemmanage.currency.service.CurrencyService;

@Scope("prototype")
@Controller
public class CurrencyController extends BaseController {

	private static Logger logger = LoggerFactory.getLogger(CurrencyController.class);

	@RequestMapping(value = "/systemmanage/currency/queryCurrencyList.web")
	public String queryCurrencyList(HttpServletRequest request, HttpServletResponse response, Model model) {
		
		return "/WEB-INF/jsp/systemmanage/currency/currencyList";
	}

	@RequestMapping(value = "/systemmanage/currency/queryCurrencyListInfoDataGrid.json", method = RequestMethod.POST)
	public void queryCurrencyListInfoDataGrid(HttpServletRequest request, HttpServletResponse response, Model model) {

		PangingParam pangingParam = null;
		DataResult dataResult = new DataResult();
		DataGrid dataGrid = null;

		try {
			pangingParam = (PangingParam) ServletUtils.getParametersToBaseEntity(request, PangingParam.class);
			HashMap<String, Object> map = (HashMap) ServletUtils.getParametersToHashMap(request);
			dataGrid = new DataGrid();
			dataGrid.setPangingParam(pangingParam);

			map.put("startrow", dataGrid.getStartrow());
			map.put("endrow", dataGrid.getEndrow());
			map.put("rows", dataGrid.getRows());
			map.put("sort", dataGrid.getSort());
			map.put("order", dataGrid.getOrder());
			map.put("statusid", SysConstant.RecordStatus.VALID);

			CurrencyService currencyService = (CurrencyService) IssTransactionContainer.getInstance(CurrencyService.class, false);
			long resultCount = currencyService.findResultCount(map);
			List<Currency> resultList = currencyService.findResultList(map);

			DataStyle dataStyle = new DataStyle();
			dataStyle.setPageIndex(pangingParam.getPage());
			dataStyle.setDataCount(resultCount);
			dataStyle.setDataList(resultList);

			dataStyle.addDepict("id", DataTypeConstant.LONG);
			dataStyle.addDepict("currencynum", DataTypeConstant.STRING);
			dataStyle.addDepict("currencyname", DataTypeConstant.STRING);
			dataStyle.addDepict("currencysymbol", DataTypeConstant.STRING);
			dataStyle.addDepictByFunction("currencyposition", SysConstant.YesOrNo.class, "getName", new Class[] { long.class });
			dataResult = PangingTools.buildResultPagerInfo(dataStyle);

			if (pangingParam.getReportExportType() == 0) {
				response.getWriter().write(JSONFactory.toJSONString(dataResult, userContext));
			}

		}catch(ServiceException e)
		{
			System.out.println("123123");
			e.printStackTrace();
		}
		catch (Exception e) {
			e.printStackTrace();
			userContext.setErrorMessage(MessageResourcesUtils.getMessage(request, "alertinfo.common.java.alert5"));
		}
	}

	@RequestMapping(value = "/systemmanage/currency/toAddCurrency.web")
	public String toAddCurrency(HttpServletRequest request, HttpServletResponse response, Model model) {
		return "/WEB-INF/jsp/systemmanage/currency/currencyAdd";
	}

	@RequestMapping(value = "/systemmanage/currency/addCurrency.web", method = { RequestMethod.GET, RequestMethod.POST })
	public String addCurrency(HttpServletRequest request, HttpServletResponse response, Model model) {
		Currency currency = null;
		try {
			currency = (Currency) ServletUtils.getParametersToBaseEntity(request, Currency.class);
			String updateposition = getRequest().getParameter("updateposition");
			currency.setInputtime(new Date());
			currency.setInputuserid(userContext.getLoginUser().getId());
			currency.setModifytime(new Date());
			currency.setModifyuserid(userContext.getLoginUser().getId());
			currency.setStatusid(SysConstant.RecordStatus.VALID);
			CurrencyService currencyService = (CurrencyService) IssTransactionContainer.getInstance(CurrencyService.class, true);
			if(SysConstant.YesOrNo.YES == new Long(updateposition).longValue()){
				currencyService.updateAllCurrencyposition(SysConstant.YesOrNo.NO);
			}
			currencyService.add(currency);
			userContext.setInfoMessage(MessageResourcesUtils.getMessage(request, "alertinfo.common.java.alert1"));
			userContext.setCloseWindow(true);
		} catch (Exception e) {
			e.printStackTrace();
			userContext.setErrorMessage(MessageResourcesUtils.getMessage(request, "alertinfo.common.java.alert2"));
		}
		return "/WEB-INF/jsp/systemmanage/currency/currencyAdd";
	}

	@RequestMapping(value = "/systemmanage/currency/deleteCurrency.json", method = { RequestMethod.GET, RequestMethod.POST })
	public void deleteCurrency(HttpServletRequest request, HttpServletResponse response, Model model) {
		AjaxDataEntity ajaxDataEntity = new AjaxDataEntity();
		try {
			Long currencyId = Long.valueOf(getRequest().getParameter("id"));
			Currency currency = new Currency();
			currency.setId(currencyId);
			currency.setStatusid(SysConstant.RecordStatus.INVALID);
			CurrencyService currencyService = (CurrencyService) IssTransactionContainer.getInstance(CurrencyService.class, false);
			currencyService.update(currency);
			userContext.setInfoMessage(MessageResourcesUtils.getMessage(request, "alertinfo.common.java.alert3"));
			response.getWriter().write(JSONFactory.toJSONString(ajaxDataEntity, userContext));
		} catch (Exception e) {
			e.printStackTrace();
			userContext.setErrorMessage(MessageResourcesUtils.getMessage(request, "alertinfo.common.java.alert4"));
		}
	}

	@RequestMapping(value = "/systemmanage/currency/toUpdateCurrency.web")
	public String toUpdateCurrency(HttpServletRequest request, HttpServletResponse response, Model model) {
		try {
			String currencyId = getRequest().getParameter("id");
			CurrencyService currencyService = (CurrencyService) IssTransactionContainer.getInstance(CurrencyService.class, false);
			Currency currency = currencyService.findCurrencyById(currencyId);
			model.addAttribute("currency", currency);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "/WEB-INF/jsp/systemmanage/currency/currencyUpdate";
	}

	@RequestMapping(value = "/systemmanage/currency/updateCurrency.web", method = { RequestMethod.GET, RequestMethod.POST })
	public String updateCurrency(HttpServletRequest request, HttpServletResponse response, Model model) {
		Currency currency = null;
		try {
			currency = (Currency) ServletUtils.getParametersToBaseEntity(request, Currency.class);
			String updateposition = getRequest().getParameter("updateposition");
			currency.setModifytime(new Date());
			currency.setModifyuserid(userContext.getLoginUser().getId());
			CurrencyService currencyService = (CurrencyService) IssTransactionContainer.getInstance(CurrencyService.class, true);
			if(SysConstant.YesOrNo.YES == new Long(updateposition).longValue()){
				currencyService.updateAllCurrencyposition(SysConstant.YesOrNo.NO);
			}
			currencyService.update(currency);
			userContext.setInfoMessage(MessageResourcesUtils.getMessage(request, "alertinfo.common.java.alert1"));
			userContext.setCloseWindow(true);
		} catch (Exception e) {
			e.printStackTrace();
			userContext.setErrorMessage(MessageResourcesUtils.getMessage(request, "alertinfo.common.java.alert2"));
		}
		return "/WEB-INF/jsp/systemmanage/currency/currencyUpdate";
	}
	
	@RequestMapping(value = "/systemmanage/currency/validattionCurrency.json", method = { RequestMethod.GET, RequestMethod.POST })
	public void validattionCurrency(HttpServletRequest request, HttpServletResponse response, Model model) {
		AjaxDataEntity ajaxDataEntity = new AjaxDataEntity();
		try {
			Currency currency = null;
			StringBuffer errorMsg = new StringBuffer();
			HashMap<String, Object> map = new HashMap<String, Object>();
			currency = (Currency) ServletUtils.getParametersToBaseEntity(request, Currency.class);
			
			CurrencyService currencyService = (CurrencyService) IssTransactionContainer.getInstance(CurrencyService.class, false);
			map.put("statusid", SysConstant.RecordStatus.VALID);
			if(null != currency.getId()){
				map.put("id", currency.getId());
			}
			map.put("currencynum", currency.getCurrencynum());
			if(!currencyService.validationCurrency(map)){
				errorMsg.append(MessageResourcesUtils.getMessage(request, "systemmanage.currency.add.currencynumexist"));
			}
			map.remove("currencynum");
			map.put("currencyname", currency.getCurrencyname());
			if(!currencyService.validationCurrency(map)){
				errorMsg.append(MessageResourcesUtils.getMessage(request, "systemmanage.currency.add.currencynameexist"));
			}
			map.remove("currencyname");
			map.put("currencysymbol", currency.getCurrencysymbol());
			if(!currencyService.validationCurrency(map)){
				errorMsg.append(MessageResourcesUtils.getMessage(request, "systemmanage.currency.add.currencysymbolexist"));
			}
			if(StringUtils.isNotEmpty(errorMsg.toString())){
				userContext.setErrorMessage(errorMsg.toString());
			}
			response.getWriter().write(JSONFactory.toJSONString(ajaxDataEntity, userContext));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
